package com.cf.studentsociety.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.logging.Logger;

@WebFilter(filterName = "LoginFilter", urlPatterns = "/*")
public class LoginFilter implements Filter {
    private static final Logger logger = Logger.getLogger(LoginFilter.class.getName());

    // 定义不需要登录验证的路径集合
    private static final Set<String> ALLOWED_PATHS = new HashSet<>(Arrays.asList(
            "/studentSociety/index.jsp",    // 首页
            "/studentSociety/loginReg.jsp", // 注册页
            "/studentSociety/",             // 网站根目录
            "/studentSociety/student/login", // 登录请求路径
            "/studentSociety/student/register"      // 注册提交路径
    ));

    @Override
    public void doFilter(ServletRequest request,
                         ServletResponse response,
                         FilterChain chain)
            throws ServletException, IOException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;

        String url = req.getRequestURI(); // 获取请求的完整路径
        HttpSession session = req.getSession(false); // 获取会话（不创建）

        // 如果是允许访问的路径，直接放行
        if (isAllowedPath(url)) {
            chain.doFilter(req, res);
            return;
        }

        // 检查用户是否登录
        String student = (session != null) ? (String) session.getAttribute("student") : null;
        if (student == null) {
            // 如果用户没有登录，重定向到登录页面，并传递提示信息
            String redirectUrl = req.getContextPath() + "/studentSociety/login.jsp?message=" + URLEncoder.encode("请先登录", "UTF-8");

            // 记录日志
            logger.warning("用户未登录，重定向到登录页: " + redirectUrl);

            res.sendRedirect(redirectUrl);
        } else {
            // 如果已登录，继续执行请求
            chain.doFilter(req, res);
        }
    }

    /**
     * 检查是否是允许直接访问的路径
     */
    private boolean isAllowedPath(String url) {
        // 精确匹配路径，支持免过滤路径
        return ALLOWED_PATHS.contains(url);
    }
}
